<?php
declare (strict_types = 1);

namespace app\model\communal;

use app\model\concern\AmisTrait;
use Carbon\Carbon;
use think\Model;
use think\db\Query;
use think\model\relation\BelongsTo;
use think\model\concern\SoftDelete;
use think\model\relation\HasOne;

class OrderConsultModel extends Model
{
    use AmisTrait;

    /**
     * 数据库配置
     *
     * @var string
     */
    protected $connection = 'communal';

    /**
     * 主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $table = '50200_order_consult';

    /**
     * 自动时间戳
     *
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间字段设置
     *
     * @var string
     */
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 软删除
     */
    use SoftDelete;
    protected $deleteTime = 'delete_at';
    protected $defaultSoftDelete = 0;

    /**
     * 展示字段名
     *
     * @var string[]
     */
    public static $column = [
        'id', 'number', 'group_id', 'user_id', 'expert_id', 'morph_id', 'refund_at', 'consult_at',
        'consult_end', 'report_at', 'status', 'refund_status' , 'refund_remark', 'name', 'amount', 'purchase_time',
        'total_amount', 'payment_amount', 'deduct_amount', 'deduct_coin', 'payment_type', 'type', 'state', 'created_at',

        /*
         * 报告
         */
        'report_at', 'report_judge', 'report_is_spirit', 'report_is_nerve', 'report_desc',

        /*
         * 企业券
         */
        'created_method', 'is_coupon',
    ];

    /**
     * 搜索字段名
     *
     * @var string[]
     */
    public static $searchColumn = [
        'id', 'user_id', 'expert_id', 'expert_ids', 'number', 'status', 'type', 'consult_at', 'state', 'createtime',
        'refund_status', 'is_coupon',
        'group_id',
    ];

    /**
     * 新增字段
     *
     * @var string[]
     */
    public static $saveColumn = [
        'user_id', 'scale_multi_id', 'scale_multi_name', 'number', 'total_amount', 'payment_amount', 'deduct_amount',
        'deduct_coin', 'payment_type', 'type', 'state'
    ];

    /**
     * 更新字段
     *
     * @var string[]
     */
    public static $updateColumn = [
        'id', 'consult_end', 'report_at', 'status', 'state'
    ];

    /**
     * @var string[]
     */
    public static $itemColumn = ['id', 'status', 'state'];

    /**
     * 排序选项
     */
    const ORDER_OPTION_ONE = 1; // 综合排序
    const ORDER_OPTION_TWO = 2; // 时长优先

    /**
     * 排序选项 Options
     */
    public static $orderOptions = [
        ['id' => self::ORDER_OPTION_ONE, 'name' => '综合排序'],
        ['id' => self::ORDER_OPTION_TWO, 'name' => '时长优先'],
    ];

    /**
     * 排序规则映射
     *
     * @var string[]
     */
    public static $orderRuleMap = [
        1 => ['orderBy' => 'created_at', 'orderDir' => 'desc'],
        2 => ['orderBy' => 'purchase_time', 'orderDir' => 'desc'],
    ];


    /**
     * 订单类别选项 Options
     */
    public static $typeOptions = [
        ['id' => 1, 'name' => '量表解读'],
        ['id' => 2, 'name' => '专家咨询'],
    ];

    /**
     * 企业券 选项 Options
     */
    public static $couponOptions = [
        ['id' => 1, 'name' => '个人'],
        ['id' => 2, 'name' => '企业'],
    ];


    /**
     * 订单状态选项 Options
     * 订单常规状态 1 待支付 2 待预约时间 3 待开始 4 进行中 5 待填写报告 6 已完成 7 已取消
     * 订单退款状态 1 未退款/取消 2 发起退款/退款审核 3 审核通过 4 审核驳回
     */
    public static $statusOptions = [
        // ['id' => 0, 'name' => '全部'],
        ['id' => 1, 'name' => '待支付'],
        ['id' => 2, 'name' => '待预约时间'],
        ['id' => 3, 'name' => '待开始'],
        ['id' => 4, 'name' => '进行中'],
        ['id' => 5, 'name' => '待填写报告'],
        ['id' => 6, 'name' => '已完成'],
        ['id' => 7, 'name' => '已取消'],

        /*
         * 退款状态
         */
        ['id' => 102, 'name' => '退款审核'],
        ['id' => 103, 'name' => '退款成功'],
    ];


    /**
     * 对求助者初步判断 选项 Options
     */
    public static $judgeOptions = [
        ['id' => 1, 'name' => '一般心理问题'],
        ['id' => 2, 'name' => '较严重心理问题'],
        ['id' => 3, 'name' => '很严重心理问题'],
    ];

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getRefundAtAttr($value, $data)
    {
        return empty($value) ? '' : Carbon::createFromTimestamp($value)->format('Y-m-d H:i:s');
    }

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getConsultEndAttr($value, $data)
    {
        return empty($value) ? '' : Carbon::createFromTimestamp($value)->format('Y-m-d H:i:s');
    }

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getReportAtAttr($value, $data)
    {
        return empty($value) ? '' : Carbon::createFromTimestamp($value)->format('Y-m-d H:i:s');
    }

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getConsultAtAttr($value, $data)
    {
        return empty($value) ? '' : Carbon::createFromTimestamp($value)->format('Y-m-d H:i:s');
    }

    /**
     * user_id
     *
     * @param Query $query
     * @param $value
     */
    public function searchUserIdAttr(Query $query, $value)
    {
        if (!empty($value)) {
            $query->where('user_id', $value);
        }
    }

    /**
     * expert_id
     *
     * @param Query $query
     * @param $value
     */
    public function searchExpertIdAttr(Query $query, $value)
    {
        if (!empty($value)) {
            $query->where('expert_id', $value);
        }
    }

    /**
     * @param Query $query
     * @param $value
     */
    public function searchTypeAttr(Query $query, $value)
    {
        if (!empty($value)) {
            $query->where('type', $value);
        }
    }

    /**
     * @param Query $query
     * @param $value
     */
    public function searchIsCouponAttr(Query $query, $value)
    {
        if (!empty($value)) {
            $query->where('is_coupon', $value);
        }
    }

    /**
     * status 搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchStatusAttr(Query $query, $value)
    {
        // 支持多选
        if (!empty($value)) {
            $status = explode(',', $value);
            // 退款状态
            $refundStatus = [];
            if (in_array(102, $status)) {
                $refundStatus[] = 2;
            }
            if (in_array(103, $status)) {
                $refundStatus[] = 3;
            }
            // 常规状态
            // 按状态查
            $query->where('refund_status', 'in', $refundStatus)
                ->whereOr('status', 'in', $status);

            // 时间需求不要了,就是这么随意-!-🤢🤢🤢
            // $query->where(function (Query $query) use ($refundStatus, $status) {
            //     if ((in_array(3, $status) && in_array(4, $status))
            //         || (!in_array(3, $status) && !in_array(4, $status))
            //     ) {
            //         // 按状态查
            //         $query->where('refund_status', 'in', $refundStatus)
            //             ->whereOr('status', 'in', $status);
            //     } elseif (in_array(3, $status)) {
            //         // 待开始
            //         $key = array_search(3, $status);
            //         unset($status[$key]);
            //         $query->where('refund_status', 'in', $refundStatus)
            //             ->whereOr('status', 'in', $status)
            //             ->whereOr(function (Query $query) {
            //                 $query->where('status', 3)
            //                     ->where('consult_at', '>', Carbon::now()->timestamp);
            //             });
            //     } elseif (in_array(4, $status)) {
            //         // 进行中
            //         $key = array_search(3, $status);
            //         unset($status[$key]);
            //         $query->where('refund_status', 'in', $refundStatus)
            //             ->whereOr('status', 'in', $status)
            //             ->whereOr(function (Query $query) {
            //                 $query->where('status', 3)
            //                     ->where('consult_at', '<=', Carbon::now()->timestamp);
            //             });
            //     }
            // });
        }
    }

    /**
     * expert_ids 搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchExpertIdsAttr(Query $query, $value)
    {
        if (!empty($value)) {
            $query->whereIn('expert_id', $value);
        }
    }

    /**
     * number 搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchNumberAttr(Query $query, $value)
    {
        if (!is_null($value) && strlen((string)$value) > 0) {
            $query->where('number', 'like', '%' . $value . '%');
        }
    }

    /**
     * consult_at 时间范围搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchConsultAtAttr($query, $value)
    {
        if (!empty($value)) {
            $range = explode(',', $value);
            $start = $range[0];
            $end = $range[1];
            $query->where('consult_at', '>=', $start);
            $query->where('consult_at', '<=', $end);
        }
    }

    /**
     * 附表
     *
     * @return HasOne
     */
    public function hasSub()
    {
        return $this->hasOne(OrderMultiSubModel::class, 'order_multi_id', 'id')
            ->bind([
                'order_multi_type' => 'order_multi_type',
                'order_multi_topic' => 'order_multi_topic',
                'order_multi_result' => 'order_multi_result',
            ]);
    }

    /**
     * @return BelongsTo
     */
    public function belongMulti()
    {
        return $this->belongsTo(ScaleMultiModel::class, 'scale_multi_id', 'id')
            ->bind([
                'multi_evaluation_number' => 'evaluation_number'
            ]);
    }

    /**
     * @return BelongsTo
     */
    public function belongUser()
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id')
            ->bind([
                'user_name' => 'name'
            ]);
    }

    /**
     * @return BelongsTo
     */
    public function belongExpert()
    {
        return $this->belongsTo(UserExpertModel::class, 'expert_id', 'id')
            ->bind([
                'expert_name' => 'name',
                'expert_avatar' => 'avatar'
            ]);
    }
}
